package com.clickpaas.governmentcloud.utils.dateutils;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class DateUtils {
	
	private static transient int gregorianCutoverYear = 1582;
	
	/** 闰年中每月天数 */
	private static final int[] DAYS_P_MONTH_LY= {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
	
	/** 非闰年中每月天数 */
	private static final int[] DAYS_P_MONTH_CY= {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
	
	/** 代表数组里的年、月、日 */
	private static final int Y = 0, M = 1, D = 2;
	
    public static List<String> getMonthBetween(String minDate, String maxDate) throws Exception {
	    ArrayList<String> result = new ArrayList<String>();
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月
 
	    Calendar min = Calendar.getInstance();
	    Calendar max = Calendar.getInstance();
 
	    min.setTime(sdf.parse(minDate));
	    min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
 
	    max.setTime(sdf.parse(maxDate));
	    max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
 
	    Calendar curr = min;
	    while (curr.before(max)) {
	     result.add(sdf.format(curr.getTime()));
	     curr.add(Calendar.MONTH, 1);
	    }
	    min = null;max = null;curr = null;
	    return result;
	  }
    
    /**
    * 将代表日期的字符串分割为代表年月日的整形数组
    * @param date
    * @return
    */
    public static int[] splitYMD(String date){
    	date = date.replace("-", "");
    	int[] ymd = {0, 0, 0};
    	ymd[Y] = Integer.parseInt(date.substring(0, 4));
    	ymd[M] = Integer.parseInt(date.substring(4, 6));
    	ymd[D] = Integer.parseInt(date.substring(6, 8));
    	return ymd;
    }

    /**
    * 检查传入的参数代表的年份是否为闰年
    * @param year
    * @return
    */
    public static boolean isLeapYear(int year) {
    	return year >= gregorianCutoverYear ?
    			((year%4 == 0) && ((year%100 != 0) || (year%400 == 0))) : (year%4 == 0);
    }

    /**
    * 日期加1天
    * @param year
    * @param month
    * @param day
    * @return
    */
    private static int[] addOneDay(int year, int month, int day){
	    if(isLeapYear( year )){
	    	day++;
		    if( day > DAYS_P_MONTH_LY[month -1 ] ){
		    	month++;
		    	if(month > 12){
		    		year++;
		    		month = 1;
		    	}
		    	day = 1;
		    }
	    }else{
	    	day++;
	    	if( day > DAYS_P_MONTH_CY[month -1 ] ){
    			month++;
    			if(month > 12){
    				year++;
    				month = 1;
    			}
    			day = 1;
	    	}
    	}
	    int[] ymd = {year, month, day};
	    return ymd;
    }

    /**
    * 将不足两位的月份或日期补足为两位
    * @param decimal
    * @return
    */
    public static String formatMonthDay(int decimal){
    	DecimalFormat df = new DecimalFormat("00");
    	return df.format( decimal );
    }

    /**
    * 将不足四位的年份补足为四位
    * @param decimal
    * @return
    */
    public static String formatYear(int decimal){
    	DecimalFormat df = new DecimalFormat("0000");
    	return df.format( decimal );
    }

    /**
    * 计算两个日期之间相隔的天数
    * @param begin
    * @param end
    * @return
    * @throws ParseException
    */
    public static long countDay(String begin,String end){
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    	Date beginDate , endDate;
    	long day = 0;
    	try {
    		beginDate= format.parse(begin);
    		endDate= format.parse(end);
    		day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);
    	} catch (ParseException e) {
    		e.printStackTrace();
    	}
    	return day;
    }
    
    /**
    * 以循环的方式计算日期
    * @param beginDate
    * @param endDate
    * @return
    */
    public static List<String> getEveryday(String beginDate , String endDate){
    	long days = countDay(beginDate, endDate);
    	int[] ymd = splitYMD( beginDate );
    	List<String> everyDays = new ArrayList<String>();
    	everyDays.add(beginDate);
    	for(int i = 0; i < days; i++){
    		ymd = addOneDay(ymd[Y], ymd[M], ymd[D]);
    		everyDays.add(formatYear(ymd[Y])+"-"+formatMonthDay(ymd[M])+"-"+formatMonthDay(ymd[D]));
    	}
    	return everyDays;
    }
    
    /**
     * 根据周数，获取开始日期、结束日期
     * @param week  周期  0本周，-1上周，-2上上周，1下周，2下下周
     * @return  返回date[0]开始日期、date[1]结束日期
     */
    public static Date[] getWeekStartAndEnd(int week) {
        DateTime dateTime = new DateTime();
        LocalDate date = new LocalDate(dateTime.plusWeeks(week));
        date = date.dayOfWeek().withMinimumValue();
        Date beginDate = date.toDate();
        Date endDate = date.plusDays(6).toDate();
        return new Date[]{beginDate, endDate};
    }
    
    /**
	 * 获取指定日期所在月份开始的时间
	 * 时间格式yyyyMMdd
	 * @param date 指定日期
	 * @return
	 */
	public static String getMonthBegin(Date date) {
		SimpleDateFormat aDateFormat=new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		
		//设置为1号,当前日期既为本月第一天  
		c.set(Calendar.DAY_OF_MONTH, 1);
		//将小时至0  
		c.set(Calendar.HOUR_OF_DAY, 0);  
		//将分钟至0  
		c.set(Calendar.MINUTE, 0);  
		//将秒至0  
		c.set(Calendar.SECOND,0);  
		//将毫秒至0  
		c.set(Calendar.MILLISECOND, 0);  
		// 获取本月第一天的时间
		return aDateFormat.format(c.getTime());  
	}
	
	/**
	 * 获取指定日期所在月份结束的时间
	 * 时间格式yyyyMMdd
	 * @param date 指定日期
	 * @return
	 */
	public static String getMonthEnd(Date date) {
		SimpleDateFormat aDateFormat=new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();  
		c.setTime(date);
		
		//设置为当月最后一天
		c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));  
		//将小时至23
		c.set(Calendar.HOUR_OF_DAY, 23);  
		//将分钟至59
		c.set(Calendar.MINUTE, 59);  
		//将秒至59
		c.set(Calendar.SECOND,59);  
		//将毫秒至999
		c.set(Calendar.MILLISECOND, 999);  
		// 获取本月最后一天的时间 
		return aDateFormat.format(c.getTime());
	}
	
	
	/**
	 * 秒转 天 小时 分钟 秒
	 * @param secondsTime
	 */
	public static void getDayHoursMinutesSeconds(String secondsTime) {
		try {
			Integer seconds = Integer.parseInt(secondsTime) ;
			int day=0, hours=0, minutes=0;
			day = seconds / (60 * 60 * 24);
			seconds -= day * 60 * 60 * 24;
			hours = seconds / (60 * 60);
			seconds -= hours * 60 * 60;
			minutes = seconds / 60;
			seconds -= minutes * 60;
			
			if(day != 0) {
				System.out.println("总共耗时: " + day + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒");
			} else if(hours != 0) {
				System.out.println("总共耗时: " + hours + "小时" + minutes + "分钟" + seconds + "秒");
			} else if(minutes != 0) {
				System.out.println("总共耗时: " + minutes + "分钟" + seconds + "秒");
			} else if(seconds != 0) {
				System.out.println("总共耗时: " + seconds + "秒");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 计算2个日期之间相差的  以年、月、日为单位，各自计算结果是多少
	 * 比如：2011-02-02 到  2017-03-02
	 *                                以年为单位相差为：6年
	 *                                以月为单位相差为：73个月
	 *                                以日为单位相差为：2220天
	 * @param fromDateStr
	 * @param toDateStr
	 * @param dayCom
	 * @return
	 * @throws ParseException 
	 */
	public static Boolean dayCompare(String fromDateStr,String toDateStr, Integer dayCom) {
		boolean result = false;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
		
		Date currDate = new Date();
		toDateStr = sdf.format(currDate);
		Date fromDate = null;
		Date toDate = null;
		try {
			fromDate = sdf.parse(fromDateStr);
			toDate = sdf.parse(toDateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	    Calendar  from  =  Calendar.getInstance();
	    from.setTime(fromDate);
	    Calendar  to  =  Calendar.getInstance();
	    to.setTime(toDate);
	    //只要年月
	    int fromYear = from.get(Calendar.YEAR);
	    int fromMonth = from.get(Calendar.MONTH);

	    int toYear = to.get(Calendar.YEAR);
	    int toMonth = to.get(Calendar.MONTH);

//	    int year = toYear  -  fromYear;
//	    int month = toYear *  12  + toMonth  -  (fromYear  *  12  +  fromMonth);
	    int day = (int) ((to.getTimeInMillis()  -  from.getTimeInMillis())  /  (24  *  3600  *  1000));
//	    DayCompare.builder().day(day).month(month).year(year).build()
//	    System.out.println("year " + year);
//	    System.out.println("month " + month);
	    if(day > dayCom) {
	    	result = true;
	    }
	    return result;
	}

	public static void main(String[] args) throws ParseException {
		String toDate = "2019/1/1";
		System.out.println(dateConvers(toDate));
	}

	public static String dateConvers(String strData) throws ParseException {
		SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy/MM/dd");
		Date date = dateFormat.parse(strData);
		SimpleDateFormat targetDF = new SimpleDateFormat( "yyyy-MM-dd");
		return targetDF.format(date);
	}

}
